package com.zbkj.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zbkj.common.annotation.LogControllerAnnotation;
import com.zbkj.common.enums.MethodType;
import com.zbkj.common.model.order.StoreOrder;
import com.zbkj.common.model.order.StoreOrderInfo;
import com.zbkj.common.model.product.StoreProductAttrValue;
import com.zbkj.common.model.user.User;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.*;
import com.zbkj.common.response.*;
import com.zbkj.common.result.CommonResult;
import com.zbkj.common.utils.CrmebDateUtil;
import com.zbkj.common.utils.CrmebUtil;
import com.zbkj.common.vo.DateLimitUtilVo;
import com.zbkj.common.vo.ExpressSheetVo;
import com.zbkj.common.vo.LogisticsResultVo;
import com.zbkj.common.vo.OrderInfoDetailVo;
import com.zbkj.service.dao.UserDao;
import com.zbkj.service.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 订单表 前端控制器
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2024 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Slf4j
@RestController
@RequestMapping("api/admin/store/order")
@Api(tags = "订单") //配合swagger使用
public class StoreOrderController {

    @Autowired
    private StoreOrderService storeOrderService;

    @Autowired
    private StoreOrderVerification storeOrderVerification;


    @Autowired
    private StoreProductService storeProductService;


    /**
     * 分页显示订单表
     *  @param request          搜索条件
     * @param pageParamRequest 分页参数
     */
    @PreAuthorize("hasAuthority('admin:order:list')")
    @ApiOperation(value = "分页列表") //配合swagger使用
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<StoreOrderDetailResponse>> getList(@Validated StoreOrderSearchRequest request, @Validated PageParamRequest pageParamRequest) {
        return CommonResult.success(storeOrderService.getAdminList(request, pageParamRequest));
    }

    /**
     * 获取订单各状态数量
     */
    @PreAuthorize("hasAuthority('admin:order:status:num')")
    @ApiOperation(value = "获取订单各状态数量")
    @RequestMapping(value = "/status/num", method = RequestMethod.GET)
    public CommonResult<StoreOrderCountItemResponse> getOrderStatusNum(
            @RequestParam(value = "dateLimit", defaultValue = "") String dateLimit,
            @RequestParam(value = "type", defaultValue = "2") @Range(min = 0, max = 2, message = "未知的订单类型") Integer type) {
        return CommonResult.success(storeOrderService.getOrderStatusNum(dateLimit, type));
    }

    /**
     * 获取订单统计数据
     */
    @PreAuthorize("hasAuthority('admin:order:list:data')")
    @ApiOperation(value = "获取订单统计数据")
    @RequestMapping(value = "/list/data", method = RequestMethod.GET)
    public CommonResult<StoreOrderTopItemResponse> getOrderData(@RequestParam(value = "dateLimit", defaultValue = "")String dateLimit) {
        return CommonResult.success(storeOrderService.getOrderData(dateLimit));
    }


    /**
     * 订单删除
     */
    @LogControllerAnnotation(intoDB = true, methodType = MethodType.DELETE, description = "删除订单")
    @PreAuthorize("hasAuthority('admin:order:delete')")
    @ApiOperation(value = "订单删除")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public CommonResult<String> delete(@RequestParam(value = "orderNo") String orderNo) {
        if (storeOrderService.delete(orderNo)) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 备注订单
     */
    @LogControllerAnnotation(intoDB = true, methodType = MethodType.UPDATE, description = "备注订单")
    @PreAuthorize("hasAuthority('admin:order:mark')")
    @ApiOperation(value = "备注")
    @RequestMapping(value = "/mark", method = RequestMethod.POST)
    public CommonResult<String> mark(@RequestParam String orderNo, @RequestParam String mark) {
        if (storeOrderService.mark(orderNo, mark)) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 修改订单(改价)
     */
    @LogControllerAnnotation(intoDB = true, methodType = MethodType.UPDATE, description = "修改订单价格")
    @PreAuthorize("hasAuthority('admin:order:update:price')")
    @ApiOperation(value = "修改订单(改价)")
    @RequestMapping(value = "/update/price", method = RequestMethod.POST)
    public CommonResult<String> updatePrice(@RequestBody @Validated StoreOrderUpdatePriceRequest request) {
        if (storeOrderService.updatePrice(request)) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    @Resource
    private UserDao userDao;

    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private StoreProductAttrValueService  storeProductAttrValueService;

    /**
     * 批量添加订单
     */
  @RequestMapping(value = "/plAddOrder", method = RequestMethod.POST)
    public CommonResult<String> plAddOrder(@RequestBody @Validated StoreOrderPlAddRequest request) {
       Integer orderNum = request.getOrderNum();
       Integer productId = request.getProductId();

       //2025-02-05
       String orderTime = request.getOrderTime();
       //根据上面的2025-02-05 随机生成一个时间  含有时分秒随机生成


      StoreProductResponse  product= storeProductService.getByProductId(productId);
      LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
      Map<String, Object> map = CollUtil.newHashMap();
      List<User> userList = userDao.findAdminList(map);
      List<StoreProductAttrValue> listByProductId = storeProductAttrValueService.getListByProductId(productId);
      StoreProductAttrValue storeProductAttrValue = RandomUtil.randomEle(listByProductId);
      for (int i = 0; i < orderNum; i++) {

           OrderInfoDetailVo detailVo = new OrderInfoDetailVo();
           detailVo.setProductId(productId);
           detailVo.setProductName(product.getStoreName());
           detailVo.setAttrValueId(1);
           detailVo.setImage(product.getImage());
           detailVo.setSku(storeProductAttrValue.getSuk());
           detailVo.setPrice(storeProductAttrValue.getPrice());
           detailVo.setPayNum(1);
           detailVo.setWeight(storeProductAttrValue.getWeight());
           detailVo.setVolume(storeProductAttrValue.getVolume());
           detailVo.setTempId(1);
           detailVo.setVipPrice(storeProductAttrValue.getPrice());
           detailVo.setIsSub(true);
           detailVo.setProductType(1);

           User user = RandomUtil.randomEle(userList);
           String orderNo = CrmebUtil.getOrderNo("order");
           StoreOrder storeOrder = new StoreOrder();
           storeOrder.setUid(user.getUid());
           storeOrder.setOrderId(orderNo);
           storeOrder.setRealName(user.getNickname());
           storeOrder.setUserPhone(user.getPhone());
           storeOrder.setUserAddress(user.getAddres());
           storeOrder.setTotalNum(1);
           storeOrder.setTotalPrice(detailVo.getPrice());
           storeOrder.setProTotalPrice(detailVo.getPrice());
           storeOrder.setTotalPostage(BigDecimal.valueOf(13));
           storeOrder.setCouponPrice(BigDecimal.valueOf(0));
           storeOrder.setPayPrice(detailVo.getPrice());
           storeOrder.setPayPostage(BigDecimal.valueOf(13));
           storeOrder.setDeductionPrice(BigDecimal.valueOf(0));
           storeOrder.setPayType(getRandomPayType());
           storeOrder.setCreateTime(getRandomTime(orderTime));
           storeOrder.setShippingType(1);
           storeOrder.setPaid(true);
           storeOrder.setCost(BigDecimal.ZERO);
           storeOrder.setType(0);
           storeOrder.setMark("订单备注");
          storeOrder.setStatus(3);
           storeOrderService.save(storeOrder);
           StoreOrderInfo soInfo = new StoreOrderInfo();
           soInfo.setProductId(detailVo.getProductId());
           soInfo.setInfo(JSON.toJSON(detailVo).toString());
           soInfo.setUnique(detailVo.getAttrValueId().toString());
           soInfo.setOrderNo(orderNo);
           soInfo.setProductName(detailVo.getProductName());
           soInfo.setAttrValueId(detailVo.getAttrValueId());
           soInfo.setImage(detailVo.getImage());
           soInfo.setSku(detailVo.getSku());
           soInfo.setPrice(detailVo.getPrice());
           soInfo.setPayNum(detailVo.getPayNum());
           soInfo.setWeight(detailVo.getWeight());
           soInfo.setVolume(detailVo.getVolume());
           soInfo.setOrderId(storeOrder.getId());
           soInfo.setGiveIntegral(0);
           soInfo.setVipPrice(detailVo.getPrice());
           storeOrderInfoService.save(soInfo);
     }
     return CommonResult.success();
  }


    /**
     * 订单详情
     */
    @PreAuthorize("hasAuthority('admin:order:info')")
    @ApiOperation(value = "详情")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public CommonResult<StoreOrderInfoResponse> info(@RequestParam(value = "orderNo") String orderNo) {
        return CommonResult.success(storeOrderService.info(orderNo));
    }

    /**
     * 发送货
     */
    @LogControllerAnnotation(intoDB = true, methodType = MethodType.UPDATE, description = "修改订单价格")
    @PreAuthorize("hasAuthority('admin:order:send')")
    @ApiOperation(value = "发送货")
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public CommonResult<String> send(@RequestBody @Validated StoreOrderSendRequest request) {
         return CommonResult.success(storeOrderService.send(request));
    }

    /**
     * 退款
     */
    @LogControllerAnnotation(intoDB = true, methodType = MethodType.UPDATE, description = "订单退款")
    @PreAuthorize("hasAuthority('admin:order:refund')")
    @ApiOperation(value = "退款")
    @RequestMapping(value = "/refund", method = RequestMethod.GET)
    public CommonResult<Boolean> refund(@Validated StoreOrderRefundRequest request) {
        return CommonResult.success(storeOrderService.refund(request));
    }

    /**
     * 拒绝退款
     */
    @LogControllerAnnotation(intoDB = true, methodType = MethodType.UPDATE, description = "订单拒绝退款")
    @PreAuthorize("hasAuthority('admin:order:refund:refuse')")
    @ApiOperation(value = "拒绝退款")
    @RequestMapping(value = "/refund/refuse", method = RequestMethod.GET)
    public CommonResult<Object> refundRefuse(@RequestParam String orderNo, @RequestParam String reason) {
        if (storeOrderService.refundRefuse(orderNo, reason)) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    /**
     * 快递查询
     */
    @PreAuthorize("hasAuthority('admin:order:logistics:info')")
    @ApiOperation(value = "快递查询")
    @RequestMapping(value = "/getLogisticsInfo", method = RequestMethod.GET)
    public CommonResult<LogisticsResultVo> getLogisticsInfo(@RequestParam(value = "orderNo") String orderNo) {
        return CommonResult.success(storeOrderService.getLogisticsInfo(orderNo));
    }

    /**
     * 核销订单头部数据
     *
     * @author stivepeim
     * @since 2020-08-29
     */
    @PreAuthorize("hasAuthority('admin:order:statistics')")
    @ApiOperation(value = "核销订单头部数据")
    @RequestMapping(value = "/statistics", method = RequestMethod.GET)
    public CommonResult<StoreStaffTopDetail> getStatistics() {
        return CommonResult.success(storeOrderVerification.getOrderVerificationData());
    }

    /**
     * 核销订单 月列表数据
     *
     * @author stivepeim
     * @since 2020-08-29
     */
    @PreAuthorize("hasAuthority('admin:order:statistics:data')")
    @ApiOperation(value = "核销订单 月列表数据")
    @RequestMapping(value = "/statisticsData", method = RequestMethod.GET)
    public CommonResult<List<StoreStaffDetail>> getStaffDetail(StoreOrderStaticsticsRequest request) {
        return CommonResult.success(storeOrderVerification.getOrderVerificationDetail(request));
    }


    /**
     * 核销码核销订单
     *
     * @author stivepeim
     * @since 2020-09-01
     */
    @LogControllerAnnotation(intoDB = true, methodType = MethodType.UPDATE, description = "核销码核销订单")
    @PreAuthorize("hasAuthority('admin:order:write:update')")
    @ApiOperation(value = "核销码核销订单")
    @RequestMapping(value = "/writeUpdate/{vCode}", method = RequestMethod.GET)
    public CommonResult<Object> verificationOrder(@PathVariable String vCode) {
        return CommonResult.success(storeOrderVerification.verificationOrderByCode(vCode));
    }

    /**
     * 核销码查询待核销订单
     *
     * @author stivepeim
     * @since 2020-09-01
     */
    @PreAuthorize("hasAuthority('admin:order:write:confirm')")
    @ApiOperation(value = "核销码查询待核销订单")
    @RequestMapping(value = "/writeConfirm/{vCode}", method = RequestMethod.GET)
    public CommonResult<Object> verificationConfirmOrder(
            @PathVariable String vCode) {
        return CommonResult.success(storeOrderVerification.getVerificationOrderByCode(vCode));
    }

    /**
     * 订单统计详情
     *
     * @author stivepeim
     * @since 2020-09-01
     */
    @PreAuthorize("hasAuthority('admin:order:time')")
    @ApiOperation(value = "订单统计详情")
    @RequestMapping(value = "/time", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dateLimit", value = "today,yesterday,lately7,lately30,month,year,/yyyy-MM-dd hh:mm:ss,yyyy-MM-dd hh:mm:ss/",
                    dataType = "String", required = true),
            @ApiImplicitParam(name = "type", value = "1=price 2=order", required = true)
    })
    public CommonResult<Object> statisticsOrderTime(@RequestParam String dateLimit,
                                                    @RequestParam Integer type) {
        return CommonResult.success(storeOrderService.orderStatisticsByTime(dateLimit, type));
    }

    /**
     * 获取面单默认配置信息
     */
    @PreAuthorize("hasAuthority('admin:order:sheet:info')")
    @ApiOperation(value = "获取面单默认配置信息")
    @RequestMapping(value = "/sheet/info", method = RequestMethod.GET)
    public CommonResult<ExpressSheetVo> getDeliveryInfo() {
        return CommonResult.success(storeOrderService.getDeliveryInfo());
    }

    @LogControllerAnnotation(intoDB = true, methodType = MethodType.UPDATE, description = "更改订单运单号")
    @PreAuthorize("hasAuthority('admin:order:tracking:number:update')")
    @ApiOperation(value = "更改订单运单号")
    @RequestMapping(value = "/update/tracking/number", method = RequestMethod.POST)
    public CommonResult<Boolean> updateTrackingNumber(@RequestBody @Validated StoreOrderSendRequest request) {
        if (storeOrderService.updateTrackingNumber(request)) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    // ===================================================================
    // 以下为视频订单部分
    // ===================================================================

    /**
     * 发货
     */
    @LogControllerAnnotation(intoDB = true, methodType = MethodType.UPDATE, description = "视频号订单发货")
    @PreAuthorize("hasAuthority('admin:order:video:send')")
    @ApiOperation(value = "视频号订单｜发送货")
    @RequestMapping(value = "/video/send", method = RequestMethod.POST)
    public CommonResult<Boolean> videoSend(@RequestBody @Validated VideoOrderSendRequest request) {
        if (storeOrderService.videoSend(request)) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    public Date getRandomTime(String dateStr) {
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate baseDate = LocalDate.parse(dateStr, dateFormatter);

        Random random = new Random();
        int hour = random.nextInt(24);
        int minute = random.nextInt(60);
        int second = random.nextInt(60);

        LocalDateTime randomDateTime = baseDate.atTime(hour, minute, second);

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String randomDateTimeStr = randomDateTime.format(dateTimeFormatter);
        System.out.println(randomDateTimeStr);

        // 将 LocalDateTime 转换为 Date
        return Date.from(randomDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    // 支付方式常量
    public static final String PAY_TYPE_WE_CHAT = "weixin"; // 微信支付
    public static final String PAY_TYPE_YUE = "yue"; // 余额支付
    public static final String PAY_TYPE_OFFLINE = "offline"; // 线下支付
    public static final String PAY_TYPE_ALI_PAY = "alipay"; // 支付宝


    public String getRandomPayType() {
        String[] payTypes = {PAY_TYPE_WE_CHAT, PAY_TYPE_YUE, PAY_TYPE_OFFLINE, PAY_TYPE_ALI_PAY};
        Random random = new Random();
        return payTypes[random.nextInt(payTypes.length)];
    }

}



